<template>
  <view class="container">
    <!-- 页面头部 -->
    <view class="header" @tap="openYearPicker">
      <!-- 总费用（固定） -->
      <view class="stat-item fixed-stat">
        <text class="stat-label">总费用</text>
        <text class="stat-value expense">¥{{ statistics.expenseTotalCosts }}</text>
      </view>

      <!-- 横向滑动的 top expenses（默认视觉显示2个） -->
      <scroll-view class="top-expenses-scroll" scroll-x="true" show-scrollbar="false" :scroll-with-animation="true">
        <view class="stat-item scrollable-stat" v-for="(expense, index) in statistics.topExpenses" :key="index">
          <text class="stat-label">{{ expense.type }}</text>
          <text class="stat-value">¥{{ expense.amount.toFixed(2) }}</text>
        </view>
      </scroll-view>

      <!-- 年份选择（加宽） -->
      <view class="year-picker-wrapper">
        <text>{{ currentYear === '全部' ? '全部' : currentYear + ' 年' }}</text>
        <up-icon name="arrow-down" class="year-picker-icon"></up-icon>
      </view>
    </view>

    <!-- 年份选择器 -->
    <up-picker :show="yearPickerShow" :columns="yearColumnsData" closeOnClickOverlay @confirm="handleYearConfirm"
      @cancel="handleYearCancel" @close="handleYearCancel">
    </up-picker>

    <!-- 费用记录列表 -->
    <view class="records-list">
      <view v-for="record in expenseRecords" :key="record.id" class="record-wrapper">
        <view class="record-item" @tap="toggleRecordDetails(record.id)"
          :class="{ expanded: expandedRecords.includes(record.id) }">
          <!-- 记录基本信息 -->
          <view class="record-header">
            <view class="record-date">
              <text class="date-dot"></text>
              <text class="date-text">{{ record.date }}</text>
            </view>
            <view class="record-amount">
              <text class="amount-value">¥{{ record.amount }}</text>
            </view>
            <view class="record-type">
              <up-tag size="mini" plain :type="getTagType(record.type)">
                {{ record.type }}
              </up-tag>
            </view>

            <!-- 右侧：打开编辑删除菜单的操作按钮，3个点 -->
            <view class="record-actions" @tap.stop="showRecordOperateMenu(record)">
              <up-icon name="more-dot-fill" size="36rpx" color="#999"></up-icon>
            </view>
          </view>

          <!-- 记录详细信息 -->
          <view v-if="expandedRecords.includes(record.id)" class="record-details">
            <view class="detail-row">
              <text class="detail-label">里程</text>
              <text class="detail-value">{{ record.mileage || '未记录' }} km</text>
            </view>
            <view class="detail-row">
              <text class="detail-label">备注</text>
              <text class="detail-value">{{ record.note || '无' }}</text>
            </view>
          </view>
        </view>
      </view>

      <!-- 空状态 -->
      <up-empty v-if="expenseRecords.length === 0" text="暂无养车记录" mode="data" style="height: 400px;">
      </up-empty>
    </view>

    <!-- 费用记录操作菜单（编辑、删除） -->
    <up-action-sheet :show="recordOperateMenuShow" :actions="recordOperateMenuList" :cancel-text="'取消'" round="12rpx"
      @select="handleRecordOperateSelect" @close="recordOperateMenuShow = false"></up-action-sheet>

    <!-- 添加记录按钮 -->
    <up-float-button @tap="addRecord" bottom="100px" backgroundColor="#4096FF" color="#FFFFFF">
    </up-float-button>

    <!-- 删除确认弹窗 -->
    <up-modal :show="deleteDialogShow" :title="'确认删除'" :content="'确定要删除这条养车记录吗？'" confirm-color="#FF4D4F"
      :confirm-text="'删除'" @confirm="confirmDelete" @cancel="deleteDialogShow = false">
    </up-modal>
  </view>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { onShow } from '@dcloudio/uni-app'
import * as expenseApi from '../../api/expense.js'
import * as carApi from '../../api/car.js'

// ======= 状态管理 =======
const expenseRecords = ref([])         // 费用记录列表
const currentCar = ref({})            // 当前车辆信息
const currentYear = ref('全部')        // 当前选择的年份
const yearPickerShow = ref(false)     // 年份选择器显示状态
const yearColumnsData = ref([])       // 年份选择器数据
const expandedRecords = ref([])       // 展开的记录ID列表
const deleteDialogShow = ref(false)   // 删除确认弹窗显示状态
const recordToDelete = ref(null)      // 待删除的记录ID

// 记录操作菜单（编辑、删除）
const recordOperateMenuShow = ref(false)
const currentActionRecord = ref(null)
const recordOperateMenuList = [
  { name: '编辑', color: '#4096FF' },
  { name: '删除', color: '#ff4d4f' }
]

// 费用类型
const expenseTypeConfig = ref([
  { value: '保养', label: '保养', tagType: 'success' },
  { value: '维修', label: '维修', tagType: 'warning' },
  { value: '保险', label: '保险', tagType: 'primary' },
  { value: '停车', label: '停车', tagType: 'danger' },
  { value: '洗车', label: '洗车', tagType: 'info' },
  { value: '过路', label: '过路', tagType: 'info' },
  { value: '年检', label: '年检', tagType: 'info' },
  { value: '其他', label: '其他', tagType: 'default' }
])

// 合计数据
const statistics = ref({
  expenseTotalCosts: '0.00',
  expenseRecordCount: 0,
  expenseAverageCost: '0.00',
  topExpenses: []
})


// ======= 年份筛选器相关函数 =======
// 初始化年份筛选器列数据（包含全部选项）
const initYearPicker = () => {
  // 生成近10年的年份选项
  const currentYear = new Date().getFullYear()
  const years = []
  for (let i = 0; i < 10; i++) {
    years.push(currentYear - i)
  }
  yearColumnsData.value = [
    ['全部', ...years]
  ]
}

// 打开年份筛选器
const openYearPicker = () => {
  yearPickerShow.value = true
}

// 年份筛选器确认处理
const handleYearConfirm = async (e) => {
  currentYear.value = e.value[0]
  await loadExpenseRecords()
  yearPickerShow.value = false
}

// 年份筛选器取消处理
const handleYearCancel = () => {
  yearPickerShow.value = false
}

// 根据费用类型获取标签样式
const getTagType = (type) => {
  const typeItem = expenseTypeConfig.value.find(item => item.value === type)
  return typeItem ? typeItem.tagType : 'default'
}


// ======= 数据加载相关函数 =======
// 加载车辆数据
const loadCarData = async () => {
  try {
    const car = await carApi.getCurrentCar()
    currentCar.value = car

    if (car && car.id) {
      initYearPicker()
      await loadExpenseRecords()
    }
  } catch (error) {
    console.error('加载车辆数据失败:', error)
    uni.$u.toast('加载车辆数据失败')
  }
}

// 加载费用记录
const loadExpenseRecords = async () => {
  if (!currentCar.value || !currentCar.value.id) return

  try {
    // 从API获取包含计算属性和统计数据的结果
    const result = await expenseApi.getExpenseRecords(
      currentCar.value.id,
      currentYear.value,
    )

    // 重置展开状态
    expandedRecords.value = []

    // 按日期降序排列
    expenseRecords.value = result.expenseRecords.sort((a, b) => new Date(b.date) - new Date(a.date))

    // 计算统计数据
    const count = result.expenseRecords.length
    const averageCost = count > 0 ? parseFloat(result.expenseTotalCosts) / count : 0

    // 支出项目
    let topExpenses = []
    const totalCost = parseFloat(result.expenseTotalCosts)

    if (count > 0) {
      // 按类型分组并计算金额
      const typeAmounts = {}
      result.expenseRecords.forEach(record => {
        if (!typeAmounts[record.type]) {
          typeAmounts[record.type] = 0
        }
        typeAmounts[record.type] += parseFloat(record.amount)
      })

      // 按金额降序排序
      topExpenses = Object.entries(typeAmounts)
        .map(([type, amount]) => ({
          type: type,
          amount: amount,
          percentage: totalCost > 0 ? Math.round((amount / totalCost) * 100) : 0
        }))
        .sort((a, b) => b.amount - a.amount)
    }

    statistics.value = {
      expenseTotalCosts: result.expenseTotalCosts,
      expenseRecordCount: count,
      expenseAverageCost: averageCost.toFixed(2),
      topExpenses: topExpenses
    }
  } catch (error) {
    console.error('加载费用记录失败:', error)
    uni.$u.toast('加载费用记录失败')
  }
}


// ======= 记录操作相关函数 =======
// 切换记录详情展开状态
const toggleRecordDetails = (recordId) => {
  const index = expandedRecords.value.indexOf(recordId)
  if (index > -1) {
    expandedRecords.value.splice(index, 1)
  } else {
    expandedRecords.value.push(recordId)
  }
}

// 打开记录操作菜单
const showRecordOperateMenu = (record) => {
  currentActionRecord.value = record
  recordOperateMenuShow.value = true
}

// 记录操作菜单选择
const handleRecordOperateSelect = (item) => {
  if (item.name === '编辑') {
    editRecord(currentActionRecord.value)
  } else if (item.name === '删除') {
    deleteRecord(currentActionRecord.value.id)
  }
  recordOperateMenuShow.value = false
}

// 编辑记录
const editRecord = (record) => {
  // 跳转到编辑页面
  uni.navigateTo({
    url: `/pages/expense/form?carId=${currentCar.value.id}&recordId=${record.id}`
  })
}

// 添加记录
const addRecord = () => {
  // 跳转到添加页面
  uni.navigateTo({
    url: `/pages/expense/form?carId=${currentCar.value.id}`
  })
}

// 删除记录
const deleteRecord = (recordId) => {
  recordToDelete.value = recordId
  deleteDialogShow.value = true
}

// 确认删除
const confirmDelete = async () => {
  if (!recordToDelete.value) return

  try {
    const success = await expenseApi.deleteExpenseRecord(recordToDelete.value)

    if (success) {
      await loadExpenseRecords()
      deleteDialogShow.value = false
      uni.$u.toast('删除成功')
    } else {
      uni.$u.toast('删除失败')
    }
  } catch (error) {
    console.error('删除记录失败:', error)
    uni.$u.toast('删除失败，请重试')
  }
}

// ======= 初始化 =======
const initApp = async () => {
  const app = getApp();
  await app.waitForDBReady();
  console.log('加载养车数据...');
  await loadCarData();
}

onMounted(async () => {
  await initApp();
});

onShow(async () => {
  await initApp();
})
</script>

<style lang="scss" scoped>
/* 容器样式 */
.container {
  padding: 20rpx;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.header {
  background: #fff;
  border-radius: 12rpx;
  padding: 30rpx;
  margin-bottom: 30rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
  display: flex;
  align-items: center;
}

/* 总费用 */
.fixed-stat {
  flex-shrink: 0;
  width: 140rpx;
  text-align: center;
  margin-right: 10rpx;
}

/* 横向滚动区域 */
.top-expenses-scroll {
  display: flex;
  flex: 1;
  white-space: nowrap;
  overflow: hidden;
  min-width: 0;
  max-width: 340rpx;
}

.scrollable-stat {
  display: inline-block;
  min-width: 120rpx;
  text-align: center;
  padding: 0 10rpx;
  flex-shrink: 0;
}

/* 年份选择器 */
.year-picker-wrapper {
  flex-shrink: 0;
  display: flex;
  align-items: center;
  margin-left: 20rpx;
  min-width: 140rpx;
  justify-content: flex-end;
}

.year-picker-wrapper text {
  font-size: 28rpx;
  color: #333;
}

.year-picker-icon {
  margin-left: 8rpx;
  font-size: 24rpx;
  color: #999;
}

/* 记录列表 */
.records-list {
  margin-bottom: 120rpx;
}

.record-wrapper {
  margin-bottom: 20rpx;
}

/* 记录项 */
.record-item {
  background: #fff;
  border-radius: 12rpx;
  padding: 24rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
  transition: all 0.3s;
}

.record-item.expanded {
  border-bottom: 1px solid #f0f0f0;
}

/* 记录头部 */
.record-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.record-amount {
  text-align: center;
  flex: 1;
}

.amount-value {
  font-size: 32rpx;
  font-weight: bold;
  color: #ff4d4f;
}

.record-date {
  display: flex;
  align-items: center;
}

.date-dot {
  width: 16rpx;
  height: 16rpx;
  background-color: #1890ff;
  border-radius: 50%;
  margin-right: 12rpx;
  display: inline-block;
}

.date-text {
  font-size: 30rpx;
  color: #333;
  font-weight: 500;
}

.record-type {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
}

/* 记录操作按钮 */
.record-actions {
  padding-left: 20rpx;
  display: flex;
  align-items: center;
}

/* 记录详情 */
.record-details {
  margin-top: 20rpx;
  padding: 20rpx;
  background-color: #f5f5f5;
  border-radius: 8rpx;
}

/* 统计数据样式 */
.stat-item {
  text-align: center;
}

.stat-value {
  font-size: 24rpx;
  font-weight: bold;
  color: #333;
  display: block;
}

.stat-value.expense {
  color: #ff4d4f;
}

.stat-label {
  font-size: 20rpx;
  color: #999;
  display: block;
  margin-bottom: 6rpx;
}

/* 单位样式 */
.detail-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12rpx 0;
}

.detail-label {
  font-size: 28rpx;
  color: #666;
}

.detail-value {
  font-size: 28rpx;
  color: #333;
}
</style>